// 获取md5
importScripts("/static/js/md5.js");
const md5 = self.SparkMD5;
// 对文件分片并且进行包装后返回
function createChunk(file, index, size) {
	// 定义参数
	const start = index * size;
	const end = (index + 1) * size;
	const blob = file.slice(start, end);

	// 函数hash
	const fileReader = new FileReader();
	const spark = new md5.ArrayBuffer();
	fileReader.readAsArrayBuffer(blob);

	// 获取Promise
	const { promise, resolve } = Promise.withResolvers();

	// 文件读取完成后进行hash
	fileReader.onload = function (e) {
		spark.append(e.target.result);
		resolve({
			blob,
			index,
			start,
			end,
			hash: spark.end(),
		});
	};
	return promise;
}

self.addEventListener("message", (message) => {
	const { file, size, startIndex, endIndex } = message.data;
	const result = [];
	let nums = 0;
	for (let i = startIndex; i < endIndex; i++) {
		createChunk(file, i, size).then((chunk) => {
			result[i - startIndex] = chunk;
			nums++;
			if (nums === endIndex - startIndex) {
				self.postMessage(result);
			}
		});
	}
});
